import java.util.Iterator;

import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.classic.Session;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import cn.aben.entity.Jd;
import cn.aben.entity.Xq;

  
public class Damo {
	Session session=null;
	@Before
	public void initSession(){
		Configuration cfg= new Configuration().configure();
          SessionFactory factory=cfg.buildSessionFactory();
          session=factory.openSession();
	}
	@Test
	public void add(){
		
		Transaction tr =session.beginTransaction();
		
		Xq xq =new Xq("金水区");
		session.save(xq);
		
		Jd jd1=new Jd("金水路",xq);
		Jd jd2=new Jd("文化路",xq);
		Jd jd3=new Jd("花园路",xq);
		session.save(jd1);
		session.save(jd2);
		session.save(jd3);
		tr.commit();
	}
	
	@Test
	public void manyToOne(){
		Jd jd=(Jd) session.get(Jd.class, 2);
		System.out.println(jd.getJdname()+"的区县是");
		System.out.println(jd.getXq().getXqname());
		
	}
	@Test
	public void oneToMany(){
	Xq xq=	(Xq) session.get(Xq.class, 1);
		System.out.println(xq.getXqname()+"下面的街道有");
		System.out.println(xq.getJds().size()+"个，分别是：");
		Iterator<Jd> jsd=xq.getJds().iterator();
		while(jsd.hasNext())
		{
			System.out.println(jsd.next().getJdname());
		}
	}
	/**
	 * 先不初始化区县后加
	 */
	@Test
	public void addMangToOne(){
		Transaction tr= session.beginTransaction();
		Jd jd1=new Jd("二七路");
		Jd jd2=new Jd("解放路");
		Jd jd3=new Jd("人民路");
		session.save(jd1);
		session.save(jd2);
		session.save(jd3);
		
		Xq xq= new Xq("二七区");
		
		xq.getJds().add(jd1);
		xq.getJds().add(jd2);
		xq.getJds().add(jd3);
		session.save(xq);
		tr.commit();
		
		
	}
	@Test
	/**
	 * 删除多的一方，需要从数据库和对象中同时删除
	 */
	public void deleteMany(){
		
		Transaction tr =session.beginTransaction();
		Xq xq=(Xq) session.get(Xq.class, 5);
		Jd jd =(Jd) session.get(Jd.class, 15);
		//先删除对象中的jd在删除数据库中的街道
		xq.getJds().remove(jd);
		session.delete(jd);
		tr.commit();
	}
	
	/**
	 * 删除一
	 *的一方，需要级联
	 */
	@Test
	public void deleteOne(){
		Transaction tr =session.beginTransaction();
		Xq xq =(Xq) session.get(Xq.class, 5);
		session.delete(xq);
		tr.commit();
	}
	
	@After
	public void closeSession(){
		session.close();
		
	}
}
